package cn.edu.bit.ss.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.bit.dto.WebPage;

@Component
@Scope("prototype")
public class WebPageDAO implements BaseDAO {

	private String userName;
	private String password;
	private String url;
	private Connection conn;
	private PreparedStatement pstmt;
	
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {			
			e.printStackTrace();
		} 
	}
	@Autowired
	public WebPageDAO(@Qualifier("userName")String userName,@Qualifier("password")String password,@Qualifier("url")String url){
		this.userName=userName;
		this.password=password;
		this.url=url;
		try {
			conn = DriverManager.getConnection(url,userName,password);			
		} catch (SQLException e) {	
			e.printStackTrace();
		}
	}
	
	@Override
	public void create(WebPage webPage) {
		try {		
			if(conn.isClosed()){
				conn = DriverManager.getConnection(url,userName,password);
			}
			pstmt = conn.prepareStatement("INSERT INTO HugeTable VALUES(NULL,?,?,?)");
			pstmt.setString(1, webPage.getURL());
			pstmt.setString(2, webPage.getTitle());
			pstmt.setString(3, webPage.getContent());
			pstmt.execute();
		} catch (SQLException e) {		
			e.printStackTrace();
		}
		
	}
	
	public void dispose(){
		
		try {
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {				
			e.printStackTrace();
		}finally{
			try{
				if(pstmt!=null){
					pstmt.close();
				}
			}catch (SQLException e){
				e.printStackTrace();
			}			
		}		
	}


	@Override
	public boolean checkIfExisted(WebPage webPage) {
		boolean result = false;
		try {
			if(conn.isClosed()){
				conn = DriverManager.getConnection(url,userName,password);
			}
			pstmt = conn.prepareStatement("SELECT * FROM HugeTable WHERE URL=?");		
			pstmt.setString(1, webPage.getURL());
			result = pstmt.executeQuery().next();
		} catch (SQLException e) {		
			e.printStackTrace();
		}
		return result;
	}	
	
		
	
	@Override
	public String toString(){
		return userName+password+url;
	}


	@Override
	public ArrayList<String> getStartUrl() {
		ResultSet rs;
		try {		
			if(conn.isClosed()){
				conn = DriverManager.getConnection(url,userName,password);
			}
			pstmt = conn.prepareStatement("SELECT url FROM HugeTable ORDER BY id DESC LIMIT 0,100");
			rs = pstmt.executeQuery();
			ArrayList<String> strQueue = new ArrayList<String>(100);
			while(rs.next()){
				strQueue.add(rs.getString(1));
			}
			return strQueue;
		} catch (SQLException e) {		
			e.printStackTrace();
			return null;
		}
	}
}
